package com.niezhiliang.netty.websocket.spring.boot.demo.service.other;

import com.niezhiliang.netty.websocket.spring.boot.demo.service.other.handler.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.util.List;

public class UdpClient {

    private final String host;
    private final int port;

    private ChannelFuture future;

    public UdpClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public String sendMessageToUdpServer(String content){
        //DatagramPacket datagramPacket = new DatagramPacket(Unpooled.copiedBuffer("80 10 35 01 FF 00 00 05 01 06 11 F4 00 01 0C C4 55 D5".getBytes()),new InetSocketAddress(host, port));
        content = "netty"+content;
        DatagramPacket datagramPacket = new DatagramPacket(Unpooled.copiedBuffer(content.getBytes()),new InetSocketAddress(host, port));

        this.future.channel().writeAndFlush(datagramPacket);
        try {
            this.future.channel().closeFuture().addListener(ChannelFutureListener.CLOSE);
        }catch (Exception e){
            e.printStackTrace();
        }

        return "";
    }

    public UdpClient start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        protected void initChannel(NioDatagramChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                            ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
                            ch.pipeline().addLast(new NettyClientHandler());

                        }
                    });

            ChannelFuture future = bootstrap.connect(host, port).sync();
            Channel channel = future.channel();
            channel.closeFuture().sync();
            return this;
        } finally {
            group.shutdownGracefully();
        }
    }



    public static void main(String[] args) throws InterruptedException {
        new UdpClient("localhost", 10001).start();
    }
}
